<?php
	//error_reporting(0);
	set_time_limit(E_ALL);
	ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)');
	include 'simplehtmldom/simple_html_dom.php';
	include_once(dirname(__FILE__).'/dbutil.php');
	function saveRecord($table,$record,$db){
    	if(empty($table))
    		return false;
    	if(!is_array($record) || empty($record))
    		return false;
    	//$db = new DBUtil();
    	//$this->initDB();
    	$r = array();
    	foreach($record as $key=>$item){
    		$r[$db->escape($key)] = $db->escape($item);
    	}
    	$cols = implode("," , array_keys($r));
    	$values = implode("','" , $r);
    	$sql = "insert into " . $db->escape($table) . " (" . $cols . ") values ('" . $values . "')";
    	return $db->query($sql) ? $db->getlastid() : false;
    }
	echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
	$baseUrl = 'https://yichun.anjuke.com/community/';//需要修改
	// 西安安居客
	$url = $baseUrl;
	//$url = 'https://shaoxing.anjuke.com/community/p49/';
	while(true){
		$recordList = array();
		// 西安房天下
		$listPage = file_get_html($url);
		//$listPage = file_get_contents($url);
		//echo $listPage;exit;
		if(empty($listPage)){
			break;
		}
		$list = $listPage->find('div[class=li-info]');
		if(!empty($list)){
			foreach($list as $listItem){
				//var_dump(mb_convert_encoding($listItem->innertext,'utf-8','gbk'));
				$tmp = $listItem->find('a');
				if(empty($tmp)){
					echo 1;exit;
					continue;
				}
				$name = trim($tmp[0]->title);
				$tmp = $listItem->find('address');
				$adress = trim($tmp[0]->innertext);//str_ireplace('&nbsp;','',trim($tmp[0]->innertext));
				$record = array();
				$record['house_name'] = $name ;
				$record['address'] = $adress;
				//$record['city'] = 'fuzhou';
				//状态
				$record['status'] = 0;
				//var_dump($record);exit;
				$recordList[] = $record;
				//break;
			}
			//var_dump($recordList);exit;
			$db = new DBUtil();
			//var_dump($recordList);exit;
			foreach($recordList as $item){
				$h = $db->getOneRow("select id from t_house where house_name = '".$db->escape($item['house_name'])."' ");
				if(empty($h)){
					// 保存楼盘信息
					saveRecord('t_house',$item,$db);
				}
			}
			$db->close();
		}
		$nextPage = $listPage->find('div[class=page-content]')[0]->find('i[class=curr]')[0]->next_sibling();
		while(!empty($nextPage) && $nextPage->tag != 'a' ){
			$nextPage = $nextPage->next_sibling();
		}
		if(!empty($nextPage) ){
			$url = $nextPage->href;
		}else{
			echo 'finish';
			break;
		}
		//sleep(30);
		echo $url;
	}
	
	// 删除html
	function removeHtml($value){
		return preg_replace('/<.*?<\/\w+>/','',$value);
	}
	// 删除全部空格
	function removeSpace($value){
		return preg_replace('/\s+/','',$value);
	}
?>